package com.gxgeek.javabasic.javascript;

import lombok.experimental.var;

import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

/**
 * @author gaoxing
 * @create 2017-11-16 上午10:29
 */
public class Demo {
    public static void main(String[] args) throws IOException, ScriptException, NoSuchMethodException {
        ScriptEngineManager manager = new ScriptEngineManager();
        ScriptEngine engine = manager.getEngineByName("javascript");

        String jsFileName = "/Users/gaoxing/Desktop/code/study/javastudy/src/main/resources/test1.js";   // 读取js文件

        FileReader reader = new FileReader(jsFileName);   // 执行指定脚本
        engine.eval(reader);

        if(engine instanceof Invocable) {
            Invocable invoke = (Invocable)engine;    // 调用merge方法，并传入两个参数

            // c = merge(2, 3);

            String pwd = "gxgeek2017";
            String _ts = String.valueOf(System.currentTimeMillis());
            String pwdlen = String.valueOf(pwd.length());
            if(Long.valueOf(pwdlen) < 10) {
                pwdlen = "0" + pwdlen;
            }
            //2位重放因子长度+重放因子+2位密码长度+密码
            String pwdstr = _ts.length() + _ts + pwdlen + pwd;
            String pwdData = (String)invoke.invokeFunction("CryptoJS.enc.Utf8.parse", pwdstr);;
//            String pwdData = CryptoJS.enc.Utf8.parse(pwdstr);

            String cipherMode = "1";
            String eccX = "76D26598B8F8FBAFB714DC2324DDC8184B384F9FFAA8F9BF0B87BFD5EC1DCF20";
            String eccY = "2753FBFBCB99D89A2A356FEC8216765702B50C0C4F92C85D01EB42719B30238C";

//
//            String cipher = new SM2Cipher(cipherMode);
//            var userKey = cipher.CreatePoint(eccX, eccY);
//            pwdData = cipher.GetWords(pwdData.toString());
//            var encryptData = cipher.Encrypt(userKey, pwdData);
//

            String c = (String) invoke.invokeFunction("dosomething", cipherMode, eccX, eccY,pwdData);

            System.out.println("c = " + c);
        }

        reader.close();



    }
}
